﻿using CKS.Core.Framework;
using CKS.PLC.Action.System;
using FreeSql;
using MySqlX.XDevAPI.Relational;
using SqlSugar;
using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using ZR.Model.Models.ProductionControl;

namespace CKS.PLC.Action.Subscription.OP30
{
    public class DB3031_MarkingAction : SaveProcessingResults
    {
        /// <summary>
        /// 打标机状态变化通知
        /// </summary>
        /// <param name="_value"></param>
        public DB3031_MarkingAction(DecodeValue _value) : base(_value)
        {
        }

        public override AfterSaveResult AfterSaved(SaveArg e)
        {

            string coverCode = Value.GetLocationData(e.LocationId, 1).ToString();
            var record = new CksProductionRecord()
            {
                CoverCode = coverCode,
                ProductCode = Value.GetLocationData(e.LocationId, 2).ToString(),
                UploadStatus = Value.GetLocationData(e.LocationId, 3).ToInt()
            };
            ProcessData(record);
            return base.AfterSaved(e);

        }

        private void ProcessData(CksProductionRecord data)
        {
            if (data.CoverCode.IsEmpty())
                return;

            var record = GetRecordByCoverCode(data.CoverCode);
            record.CoverCode = data.CoverCode;

            string tag = "";
            (string Code, string Grade) res;
            switch (data.UploadStatus)
            {
                case 1:
                    record.ProcessingStatus = 5;
                    record.MarkingLoadingTime = DateTime.Now;
                    tag = "投入";
                    break;
                case 2:
                    record.ProcessingStatus = 6;
                    record.MarkingStartTime = DateTime.Now;
                    tag = "开始";
                    break;
                case 3:
                    record.ProcessingStatus = 7;
                    //打标完成时间 MarkingGradingTime 改为 MarkingCompletedTime
                    record.MarkingCompletedTime = DateTime.Now;
                    tag = "完成";
                    break;
                case 4:
                    //示例 P1901991-11-D:SANH25191008657:F
                    //这里需要解析条码评级信息，规则是：条码:等级
                    record.ProcessingStatus = 8;
                    res = SplitSuffixGrade(data.ProductCode);
                    record.ProductCode = res.Code;
                    record.BarcodeGrade = res.Grade;
                    
                    record.MarkingGradingTime = DateTime.Now;
                    tag = "评级";
                    break;
                default:
                    EventBus.AddLog($"打标 {record.CoverCode} 上传状态未知 {data.UploadStatus}");
                    return;
            }

            if (record.Id > 0)
                conn.Update<CksProductionRecord>()
                    .SetSource(record)
                    .UpdateColumns(a => new { a.CoverCode ,a.ProductCode,a.BarcodeGrade,
                        a.MarkingLoadingTime,a.ProcessingStatus,a.MarkingStartTime
                        ,a.MarkingCompletedTime,a.MarkingGradingTime     })
                    .ExecuteAffrows();
            else
            {
                // 格式示例 PW 250624 0001  
                string dayCacheKey = $"PW{DateTime.Now.ToString("yyMMdd")}";
                var nextSeriaNumber = GetNextSerialNumber(dayCacheKey);
                record.SerialNumber = $"{dayCacheKey}{nextSeriaNumber.ToString().PadLeft(4, '0')}";
                conn.Insert(record).ExecuteAffrows();
                conn.Update<CksKeyCache>()
                    .Set(a => a.MaxSerialNumber, nextSeriaNumber)
                   .Where(a => a.CacheKey == dayCacheKey).ExecuteAffrows();
            }
            EventBus.AddLog($"打标{tag}；工站：OP30;{record.CoverCode} 保存完成  ");

        }

        private CksProductionRecord GetRecordByCoverCode(string coverCode)
        {
            var record = conn.Select<CksProductionRecord>()
                .Where(a => a.CreatedTime > DateTime.Now.AddYears(-1) && a.CoverCode == coverCode).OrderByDescending(a => a.Id).First();
            if (record == null)
                record = new CksProductionRecord();
            return record;
        }
    }
}
